package dev.hitools.utils.kts

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner


object LifecycleExt {
    /**
     * 监听 Destroyed 的状态
     */
    fun Lifecycle.observerDestroyed(callback: () -> Unit) {
        addObserver(LifecycleObserver(this, Lifecycle.State.DESTROYED, callback))
    }

    fun Lifecycle.observerCreated(callback: () -> Unit) {
        addObserver(LifecycleObserver(this, Lifecycle.State.CREATED, callback))
    }

    /**
     * 状态回调
     */
    private class LifecycleObserver(var lifecycle: Lifecycle?, val state: Lifecycle.State, val callback: () -> Unit) :
        LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            val lifecycleState = source.lifecycle.currentState
            if (lifecycleState == state) {
                callback()
                lifecycle?.apply {
                    removeObserver(this@LifecycleObserver)
                    lifecycle = null
                }
            }
        }
    }
}
